import {
  getRoleInfo,
  getRoleInfoByCode,
  saveRoleInfo,
  deleteRoleInfo,
  getRoleMenuInfo,
  saveRoleMenuInfo,
  getMenuList
} from '@/api'
import { ResultType } from '@/types/index'
import { Effect, Reducer } from 'umi'
export interface RoleListType {
  // 角色编号
  code: string
  // 角色名称
  name: string
  // 备注
  desc: string
  // 状态[1:有效，0:无效]
  status: string
}

export interface RoleMenuType {
  code: string
  name: string
}
export interface RoleModelState {
  roleList: RoleListType[]
  roleMenu: RoleMenuType[]
  menuList: any[]
}
interface RoleModelType {
  namespace: string
  state: RoleModelState
  reducers: {
    setState: Reducer<RoleModelState>
  }
  effects: {
    function_getRoleList: Effect
    function_getRoleInfoByCode: Effect
    function_saveRoleInfo: Effect
    function_deleteRoleInfo: Effect
    function_getRoleMenuInfo: Effect
    function_saveRoleMenuInfo: Effect
    function_getMenuList: Effect
  }
}
export default <RoleModelType>{
  namespace: 'roleModel',
  state: { roleList: [], roleMenu: [], menuList: [] },
  reducers: {
    setState(state, { payload }) {
      return { ...state, ...payload }
    }
  },
  effects: {
    *function_getRoleList(action, { call, put }) {
      const result: ResultType = yield call(getRoleInfo)
      if (result.code === 200) {
        yield put({
          type: 'setState',
          payload: {
            roleList: result.obj
          }
        })
      }
    },
    *function_getRoleInfoByCode() {},
    *function_saveRoleInfo({ payload, callback }, { call, put }) {
      const result: ResultType = yield call(saveRoleInfo, payload)
      callback(result)
    },
    *function_deleteRoleInfo({ payload: { roleCode }, callback }, { call }) {
      const result: ResultType = yield call(deleteRoleInfo, roleCode)
      callback(result)
    },
    *function_getRoleMenuInfo({ payload: { roleCode } }, { call, put }) {
      const result: ResultType = yield call(getRoleMenuInfo, roleCode)
      if (result.code === 200) {
        yield put({
          type: 'setState',
          payload: {
            roleMenu: result.obj
          }
        })
      }
    },
    *function_saveRoleMenuInfo(
      { payload: { roleCode, menuCode }, callback },
      { call }
    ) {
      const result: ResultType = yield call(
        saveRoleMenuInfo,
        roleCode,
        menuCode
      )
      callback(result)
    },
    *function_getMenuList(action, { call, put }) {
      const result: ResultType = yield call(getMenuList)
      if (result.code === 200) {
        yield put({
          type: 'setState',
          payload: {
            menuList: (result.obj as any[]).filter(
              (item) => item.code != '100103'
            )
          }
        })
      }
    }
  }
}
